<template>
  <div>
    <h2>渲染数据</h2>
    <button @click="router.push('/add')">添加数据</button>
    <div>
      <input type="text" placeholder="请根据商品id查询" v-model="searchId">
      <button @click="getSearchById">搜索</button>
      <button @click="resetData">重置</button>
      <table>
        <tbody>
          <tr>
            <td>商品id</td>
            <td>商品名称</td>
            <td>商品价格</td>
            <td>商品数量</td>
            <td>操作</td>
          </tr>
          <tr v-for="item in list" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.good_name }}</td>
            <td>{{ item.good_price }}</td>
            <td>{{ item.good_count }}</td>
            <td>
              <button @click="deleteData(item.id)">删除</button>
              <button @click="updateData(item.id)">更新</button>
            </td>
          </tr>
        </tbody>

      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref,onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {getData,getDataById,deleteDataById} from '../api/RequestApi'

let searchId = ref('')
let list = ref([])
let router = useRouter()

// 首页显示所有数据
const getAllData = async ()=>{
  let res = await getData()
  list.value = res.data
}

// 搜索  获取指定的数据
const getSearchById = async ()=>{
  // console.log()
  // let id = 
  let res = await getDataById(searchId.value)
  // console.log(res)
  list.value = res.data

}

// 删除方法
const deleteData = async (id)=>{
  let res= await deleteDataById(id)
  // console.log(res)
  if(res.code === 1002){
    // 重新获取一遍数据
    getAllData()
  }
}

// 更新
const updateData = (id)=>{
  router.push(`/update/${id}`)
}


// 搜索重置
const resetData = ()=>{
  searchId.value = ''
  getAllData()

}

// 挂载阶段获取所有数据进行渲染
onMounted(()=>getAllData())


</script>

<style scoped></style>